﻿// “网格应用程序”模板在 http://go.microsoft.com/fwlink/?LinkId=234226 上有介绍
namespace Manhua2
{
    using Manhua2.Common;
    using Manhua2.Helper;
    using Manhua2.Pages;
    using Manhua2.Provider;
    using NotificationsExtensions.TileContent;
    using System;
    using System.Threading.Tasks;
    using Windows.ApplicationModel;
    using Windows.ApplicationModel.Activation;
    using Windows.Storage;
    using Windows.UI.ApplicationSettings;
    using Windows.UI.Notifications;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;

    /// <summary>
    /// 提供特定于应用程序的行为，以补充默认的应用程序类。
    /// </summary>
    sealed partial class App : Application
    {
        /// <summary>
        /// 初始化单一实例应用程序对象。这是执行的创作代码的第一行，
        /// 逻辑上等同于 main() 或 WinMain()。
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;
            this.UnhandledException += App_UnhandledException;
        }

        private async Task InitializeApp()
        {
            // 初始化数据库
            try
            {
                await DbContext.InitializeDb();
                await CoverCacheManager.DiscoverActiveDownloadsAsync();
                await Global.InitailizeAsync();
            }
            catch
            {
                // 初始化数据库出现问题
                // 继续执行， 在主页显示错误信息
            }

            NetworkHelper.StartListenNetworkStatusChanged();

            SettingsPane.GetForCurrentView().CommandsRequested += (sender, e) =>
            {
                if (e.Request.ApplicationCommands.Count != 0)
                    return;
                // e.Request.ApplicationCommands.Clear();

                SettingsCommand cmd = new SettingsCommand(
                    "privacy", "隐私",
                    (obj) =>
                    {
                        Frame frame = Window.Current.Content as Frame;
                        if (frame != null)
                            frame.Navigate(typeof(PrivacyPage));
                    });

                e.Request.ApplicationCommands.Add(cmd);

                SettingsCommand setting = new SettingsCommand(
                    "setting", "设置",
                    (obj) =>
                    {
                        Frame frame = Window.Current.Content as Frame;
                        if (frame != null)
                            frame.Navigate(typeof(SettingPage));
                    });

                e.Request.ApplicationCommands.Add(setting);
            };
        }

        private void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            // 将异常设置为已处理， 避免程序退出。
            // await Helper.ShowMessageDialog(e.Exception.Message);
        }

        /// <summary>
        /// 在应用程序由最终用户正常启动时进行调用。
        /// 当启动应用程序以执行打开特定的文件或显示搜索结果等操作时
        /// 将使用其他入口点。
        /// </summary>
        /// <param name="args">有关启动请求和过程的详细信息。</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs args)
        {
            Frame rootFrame = Window.Current.Content as Frame;

            // 不要在窗口已包含内容时重复应用程序初始化，
            // 只需确保窗口处于活动状态

            await this.InitializeApp();
            await this.SetTiles();

            if (rootFrame == null)
            {
                // 创建要充当导航上下文的框架，并导航到第一页
                rootFrame = new Frame();
                //将框架与 SuspensionManager 键关联                                
                SuspensionManager.RegisterFrame(rootFrame, "AppFrame");

                if (args != null && args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    // 仅当合适时才还原保存的会话状态
                    try
                    {
                        await SuspensionManager.RestoreAsync();
                    }
                    catch (SuspensionManagerException)
                    {
                        //还原状态时出现问题。
                        //假定没有状态并继续
                    }
                }

                // 将框架放在当前窗口中
                Window.Current.Content = rootFrame;
            }
            if (rootFrame.Content == null)
            {
                // 当未还原导航堆栈时，导航到第一页，
                // 并通过将所需信息作为导航参数传入来配置
                // 新页
                if (!rootFrame.Navigate(typeof(MainPage)))
                {
                    throw new Exception("Failed to create initial page");
                }
            }
            // 确保当前窗口处于活动状态
            Window.Current.Activate();
        }

        /// <summary>
        /// 在将要挂起应用程序执行时调用。在不知道应用程序
        /// 将被终止还是恢复的情况下保存应用程序状态，
        /// 并让内存内容保持不变。
        /// </summary>
        /// <param name="sender">挂起的请求的源。</param>
        /// <param name="e">有关挂起的请求的详细信息。</param>
        private async void OnSuspending(object sender, SuspendingEventArgs e)
        {
            try
            {
                await LocalFileProvider.CleanTempAsync();

                var deferral = e.SuspendingOperation.GetDeferral();
                await SuspensionManager.SaveAsync();
                deferral.Complete();
            }
            catch
            {
                // 不处理挂起时出现的问题。
            }
        }

        protected async override void OnSearchActivated(SearchActivatedEventArgs args)
        {
            var previousContent = Window.Current.Content;
            var frame = previousContent as Frame;

            if (frame == null)
            {
                await this.InitializeApp();
                frame = new Frame();
            }

            frame.Navigate(typeof(SearchResultPage), args.QueryText);
            Window.Current.Content = frame;

            // 确保当前窗口处于活动状态
            Window.Current.Activate();
        }

        private async Task SetTiles()
        {
            try
            {
                var folder = await ApplicationData.Current.LocalFolder.GetFolderAsync("cover");
                if (folder == null) return;

                var files = await folder.GetFilesAsync();
                if (files.Count < 12) return;
                var random = new Random((int)DateTime.Now.Ticks);

                var manager = TileUpdateManager.CreateTileUpdaterForApplication();
                manager.EnableNotificationQueue(true);

                for (int i = 0; i < 3; i++)
                {
                    var template = TileContentFactory.CreateTileWidePeekImageCollection03();

                    template.ImageMain.Src = PathToAppx(files[random.Next(0, files.Count)].Name);
                    template.ImageSmallColumn1Row1.Src = PathToAppx(files[random.Next(0, files.Count)].Name);
                    template.ImageSmallColumn1Row2.Src = PathToAppx(files[random.Next(0, files.Count)].Name);
                    template.ImageSmallColumn2Row1.Src = PathToAppx(files[random.Next(0, files.Count)].Name);
                    template.ImageSmallColumn2Row2.Src = PathToAppx(files[random.Next(0, files.Count)].Name);
                    template.TextHeadingWrap.Text = "在线漫画";

                    template.SquareContent = TileContentFactory.CreateTileSquarePeekImageAndText01();
                    ((ITileSquarePeekImageAndText01)template.SquareContent).Image.Src = template.ImageMain.Src;
                    ((ITileSquarePeekImageAndText01)template.SquareContent).TextHeading.Text = "在线漫画";

                    var tile = template.CreateNotification();
                    manager.Update(tile);
                }
            }
            catch
            {
            }
        }

        private string PathToAppx(string input)
        {
            return "ms-appdata:///local/cover/" + input;
        }
    }
}
